package com.bank;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.text.TextUtils;
import android.util.Log;

import com.bank.lenovoz5.Z5LIUZHOUBank;
import com.entity.PointBean;
import com.entity.SMSCode;
import com.receive.SMSReceiverSend;
import com.show.api.util.StringUtils;
import com.utils.ChatClient;
import com.utils.Constants;
import com.utils.FileHelper;
import com.utils.ImageView;
import com.utils.LogToFile;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.text.DecimalFormat;
import java.util.List;

import static android.os.SystemClock.sleep;
import static com.utils.ChatClient.C_updateBalance_W;
import static com.utils.ChatClient.ConfirmOrder;
import static com.utils.ChatClient.PAUSE;
import static com.utils.ChatClient.RUNING;
import static com.utils.ChatClient.S_paused_C;
import static com.utils.ChatClient.addWorkTime;
import static com.utils.ChatClient.getSerialNumber;
import static com.utils.ChatClient.getmap;
import static com.utils.ChatClient.list;
import static com.utils.ChatClient.mapDelete;
import static com.utils.ChatClient.requestSMSCode;
import static com.utils.ChatClient.setDevicesLog;
import static com.utils.ChatClient.user;
import static com.utils.Constants.orderBankName;
import static com.utils.ImageView.saveImg22;

/**
 * 柳州银行自动化脚本
 * 修改时间：2019年9月16日13:50:45
 */
@RunWith(AndroidJUnit4.class)
public class LIUZHOUBank {
    private static UiDevice mDevice;
    private static String sumMoney = "-1";
    private Context context = InstrumentationRegistry.getTargetContext();
    private static int screenHeight = 0; // 手机屏幕高度
    //金额键盘 123456789.0
    private static int[][] xy_123m = new int[][]{
            {145, 1430}, {500, 1430}, {780, 1430},
            {145, 1600}, {500, 1600}, {780, 1600},
            {145, 1750}, {500, 1750}, {780, 1750},
            {145, 1900}, {500, 1900}};

    //卡号键盘1234567890
    private static int[][] xy_Card_Number = new int[][]{
            {300, 1410}, {540, 1410}, {780, 1410},
            {300, 1590}, {540, 1590}, {780, 1590},
            {300, 1750}, {540, 1750}, {780, 1750},
            {540, 1930}};

    //字母键盘
    private static int[][] xy_abc = new int[][]{
            {84, 1400}, {186, 1400}, {293, 1400}, {389, 1400}, {493, 1400}, {606, 1400}, {715, 1400}, {818, 1400}, {918, 1400},
            {1017, 1400},
            {122, 1580}, {222, 1580}, {330, 1580}, {433, 1580}, {557, 1580}, {655, 1580}, {773, 1580}, {863, 1580}, {970, 1580},
            {222, 1770}, {334, 1770}, {442, 1770}, {544, 1770}, {654, 1770}, {754, 1770}, {860, 1770}};
    // 联想s5 特殊字符 黑色
    private static int[][] xy_zf = new int[][]{{482, 1470}, {810, 1470}, {810, 1630}, {910, 1630}};//#*&@
    private int smsFlag = 1;
    // true为测试，false为正式
    private final static boolean IS_TEST = false;
    private static String BANK_NAME = "柳州银行";
    private static String BANK_FLAG = "LIUZHOU";

    @Test
    public void demo() throws Exception {
        LogToFile.init(context, Constants.PROT);
        mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        // 启动银行
        Constants.scriptToStart(mDevice, BANK_NAME);
        screenHeight = Constants.getScreenHeight(context, BANK_NAME);
        SMSReceiverSend sMSReceiverSend = new SMSReceiverSend();
        // 注册短信广播
        Constants.registerSMSMonitor(context, sMSReceiverSend, "106980096289");
        String carrier = android.os.Build.MODEL;
        if (carrier.contains("Lenovo L78011")) {
            showLog("进入Z5");
            new Z5LIUZHOUBank(context, mDevice);
        }
        // 获取账户信息
        if (!IS_TEST) {
            Constants.getAccountInformation(Constants.getMethod(0));
        }
        Constants.tryingToReadAccountInformation(mDevice, BANK_NAME);
        // 触发登录页面
        triggerLandingPage(Constants.getMethod(0));
        // 登录页面
        Login();
    }

    /**
     * 触发登录页面
     *
     * @param method 方法名
     * @throws UiObjectNotFoundException UI异常
     */
    private void triggerLandingPage(String method) throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_20) {
                showLog("更新广告提示超时");
                break;
            }
            UiObject mBX = mDevice.findObject(new UiSelector().resourceId("cn.bolz.mobilebank" +
                    ".liuzhou:id/notice_dialog_check_box"));
            if (mBX.exists()) {
                showLog("勾选下次不再提醒");
                mBX.click();
                sleep(ChatClient.overtime_1);
            }
            UiObject mBT = mDevice.findObject(new UiSelector().resourceId("cn.bolz.mobilebank.liuzhou:id/dialog_btn_confirm"));
            if (mBT.exists()) {
                showLog("关闭通知广告");
                mBT.click();
                sleep(ChatClient.overtime_1);
            }
            UiObject mBT_updata = mDevice.findObject(new UiSelector().resourceId("android:id/button2").text("取消"));
            if (mBT_updata.exists()) {
                showLog("关闭升级弹窗");
                mBT_updata.click();
                sleep(ChatClient.overtime_1);
            }
        }

        mDevice.drag(120, screenHeight / 4, 120, screenHeight - screenHeight / 3, 20);
        sleep(ChatClient.overtime_1);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                showLog("首页点击智能转账失败");
                ChatClient.timer(method, ChatClient.errorStr);
                return;
            }
            UiObject zhuanzhang1 = mDevice.findObject(new UiSelector().text("智能转账").resourceId("cn.bolz.mobilebank" +
                    ".liuzhou:id/tvName"));
            if (zhuanzhang1.exists()) {
                //进入转账
                LogToFile.d("========", "点击智能转账");
                zhuanzhang1.click();
                break;
            }
        }
    }

    //进入登录页面补充用户信息

    private void Login() throws UiObjectNotFoundException {
        sleep(ChatClient.overtime_5);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_30) {
                LogToFile.d("========", "未找到密码输入框");
                break;
            }
            UiObject et = mDevice.findObject(new UiSelector().text("请输入登录密码").resourceId("cn.bolz.mobilebank" +
                    ".liuzhou:id/login_et_passwd"));
            if (et.exists()) {
                et.click();
                sleep(ChatClient.overtime_2);
                // 输入手机号登陆密码
                if (IS_TEST) {
                    String pad = "yuwei#*&@";
                    setClick_new(pad);
                } else {
                    // 输入手机号登陆密码
                    setClick_new(user.getPwd());
                }
                break;
            }
        }
        sleep(ChatClient.overtime_1);
        // 点击登陆页面空白处
        mDevice.click(550, 250);
        sleep(ChatClient.overtime_1);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();

            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                LogToFile.d("========", "未找到登陆按钮");
                break;
            }
            UiObject loginBu1 = mDevice.findObject(new UiSelector().resourceId("cn.bolz.mobilebank" +
                    ".liuzhou:id/login_btn_login").text("登录"));
            if (loginBu1.exists()) {
                loginBu1.click();
                break;
            }
        }
        sleep(ChatClient.overtime_3);
        //转账金额
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_20) {
                showLog("登录验证失败");
                ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                return;
            }
            UiObject webView = mDevice.findObject(new UiSelector().text("卡号转账").className("android.view.View"));
            if (!webView.exists()) {
                webView = mDevice.findObject(new UiSelector().descriptionContains("卡号转账").className("android.view.View"));
            }
            if (webView.exists()) {
                //登录成功
                ChatClient.loginS();
                sleep(ChatClient.overtime_5);
                break;
            }
        }
        setRemittance();
    }

    /**
     * 登录成功后进入转账
     */
    private void setRemittance() {
        showLog("进入等待setRemittance()");
        try {
            while (true) {
                sleep(ChatClient.overtime_2);
                ChatClient.begintime = System.currentTimeMillis();//开始时间
                while (true) {
                    long nowtime = System.currentTimeMillis();
                    if ((nowtime - ChatClient.begintime) > ChatClient.overtime_15) {
                        showLog("进入转账汇款页失败");
                        return;
                    }
                    UiObject webView = mDevice.findObject(new UiSelector().text("卡号转账").className("android.view.View"));
                    if (webView.exists()) {
                        webView.click();
                        sleep(ChatClient.overtime_2);
                        break;
                    }
                }
                sleep(ChatClient.overtime_3);
                RUNING = list.size() > 0;
                if (RUNING) {
                    orderBankName = Constants.getBank(list.get(0).getBankName(), BANK_NAME);
                    if (ConfirmOrder) {
                        // 查账
                        showLog("进入查账");
                        auditOrder();
                    } else {
                        // 转账
                        showLog("进入转账");
                        remittanceLogin();
                    }
                } else {
                    if (PAUSE) {
                        showLog("remittance");
                        remittance();
                        ChatClient.request();
                    } else {
                        showLog("S_paused_C");
                        S_paused_C();
                        sleep(ChatClient.overtime_2);
                    }
                }
            }
        } catch (UiObjectNotFoundException e) {
            setDevicesLog(e.getMessage());
            ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
            e.printStackTrace();
        }
    }

    /**
     * 获取余额
     *
     * @param isSave 除查账外其他时间查账都要保存为保证余额的实时性 true:保存到本地 false：不保存
     * @throws UiObjectNotFoundException 捕获控件异常
     */
    private void getTheBalance(boolean isSave) throws UiObjectNotFoundException {
        showLog("获取余额");
        while (true) {
            UiObject cardView = mDevice.findObject(new UiSelector().resourceId("pageA").index(0));
            UiObject transferView1 = cardView.getChild(new UiSelector().className("android.view.View").index(1));
            UiObject transferView2 = transferView1.getChild(new UiSelector().className("android.view.View").index(2));
            if (transferView2.exists()) {
                Log.d("instance(3)", "=instance(3)==========transferView1.getText()");
                if (!StringUtils.isEmpty(transferView2.getText()) && transferView2.getText().contains("可用余额")) {
                    Log.d("====---transferView1.getText()-====", transferView2.getText());
                    sumMoney = transferView2.getText().substring(transferView2.getText().indexOf("¥") + 1);
                } else {
                    Log.d("instance(3)", "=instance(3)==========transferView1.getContentDescription()");
                    if (transferView2.getContentDescription().contains("可用余额")) {
                        Log.d("====---transferView1.getText()-====", transferView2.getContentDescription());
                        sumMoney = transferView2.getContentDescription().substring(transferView2.getContentDescription()
                                .indexOf("¥") + 1);
                    }
                }
            }
            sumMoney = sumMoney.replaceAll(",", "");
            Log.d("====---money-====", "====money===:" + sumMoney);
            if (!sumMoney.equals("")) {
                if (isSave) {
                    showLog("本地保存余额");
                    String sumMoneyFile = user.getUserName() + BANK_FLAG + "_sumMoney.txt";
                    FileHelper.saveMoneySDFile(false, sumMoney, sumMoneyFile);
                }
                C_updateBalance_W(Double.parseDouble(sumMoney));
                sleep(ChatClient.overtime_5);
            }
            break;
        }
    }

    /**
     * 转账汇款
     */
    private void remittanceLogin() throws UiObjectNotFoundException {
        getTheBalance(true);
        addWorkTime(ChatClient.overtime_60);
        sleep(ChatClient.overtime_2);
        EnterTheAmount();
        //账号
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                return;
            }
            UiObject skzh = mDevice.findObject(new UiSelector().text("请输入收款账号").resourceId("RECV_ACCT_NO"));
            if (skzh.exists()) {
                skzh.click();
                sleep(ChatClient.overtime_2);
                // 点击切换数字
                mDevice.click(82, 1934);
                sleep(ChatClient.overtime_2);
                setClickCardNumber(list.get(0).getBankNo());
                sleep(ChatClient.overtime_2);
                // 点击关闭键盘
                mDevice.click(990, 1250);
                sleep(ChatClient.overtime_2);
                showLog("银行卡号输入完成");
                break;
            }
        }

        //收款人
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                return;
            }
            UiObject skr = mDevice.findObject(new UiSelector().text("请输入姓名").resourceId("RECV_NAME"));
            if (skr.exists()) {
                sleep(ChatClient.overtime_2);
                skr.setText(list.get(0).getUserName());
                break;
            }
        }
        sleep(ChatClient.overtime_3);
        UiObject textUiObject = mDevice.findObject(new UiSelector().text("收款人").className("android.view.View"));
        if (textUiObject.exists()) {
            textUiObject.click();
        }
        sleep(ChatClient.overtime_3);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        showLog("检测是否自动适配了开户行");
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showLog("自动适配成功");
                break;
            }
            UiObject textView = mDevice.findObject(new UiSelector().text("请选择收款方开户行").resourceId("RECV_BANK_NAME"));
            if (textView.exists()) {
                addWorkTime(ChatClient.overtime_30);
                textView.click();
                sleep(ChatClient.overtime_15);
                UiObject textView1 = mDevice.findObject(new UiSelector().text("请输入搜索信息").className("android.widget.EditText"));
                textView1.setText(orderBankName);
                sleep(ChatClient.overtime_5);
                UiObject textView2 = mDevice.findObject(new UiSelector().text(orderBankName).className("android.view.View"));
                if (textView2.exists()) {
                    textView2.click();
                    break;
                } else {
                    failureToReport("银行名称错误", 1);
                    back();
                    return;
                }
            }
        }
        sleep(ChatClient.overtime_3);
        showLog("滑动屏幕");
        mDevice.drag(50, 800, 50, 100, 20);
        sleep(ChatClient.overtime_5);
        while (true) {
            UiObject button = mDevice.findObject(new UiSelector().text("下一步").className("android.widget.Button").index(16));
            if (button.exists()) {
                showLog("下一步");
                button.click();
                break;
            } else {
                UiObject button1 = mDevice.findObject(new UiSelector().text("下一步").className("android.widget.Button").index(15));
                if (button1.exists()) {
                    showLog("下一步");
                    button1.click();
                    break;
                }
            }
        }
        sleep(ChatClient.overtime_3);
        showLog("检测是否需要支行信息");
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showLog("检测不需要支行信息");
                break;
            }
            UiObject textView2 = mDevice.findObject(new UiSelector().text("请选择收款方开户支行").resourceId("RECV"));
            if (textView2.exists()) {
                failureToReport("需要支行信息，银行名错误", 1);
                mDevice.pressBack();
                sleep(ChatClient.overtime_2);
                return;
            }
        }
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_5) {
                showLog("未检测到转入相同金额转账交易");
                break;
            }
            UiObject nextAD1 = mDevice.findObject(new UiSelector().resourceId("cn.bolz.mobilebank.liuzhou:id/dialog_btn_confirm")
                    .text("确定"));
            if (nextAD1.exists()) {
                showLog("检测到转入相同金额转账交易---点击确认");
                nextAD1.click();
                break;
            }
        }
        sleep(ChatClient.overtime_3);
        /*
         * 处理短信与转账密码
         */
        smsFlag = 1;
        SMSOrPwd();
        sleep(ChatClient.overtime_3);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                return;
            }
            sleep(ChatClient.overtime_3);
            UiObject state = mDevice.findObject(new UiSelector().index(0).resourceId("pageD").text("智能转账"));
            if (state.exists()) {
                LogToFile.d("====结果页====", "====跳转到结果页====");
                ChatClient.msg("<YZF>{'header':'" + ChatClient.M_TRANSFERFINISH_P + "'}</YZF>");
                sleep(ChatClient.overtime_3);
                getUserInfo();
                break;
            } else if (state.exists()) {
                if (state.getText().contains("您的汇款正在处理中")) {
                    LogToFile.d("====等待跳转到结果页====", "====等待跳转到结果页====");
                }
            }
        }
    }

    private void EnterTheAmount() throws UiObjectNotFoundException {
        //转账金额
        while (true) {
            UiObject cardSum = mDevice.findObject(new UiSelector().resourceId("TRANS_AMT").index(1));
            if (cardSum.exists()) {
                cardSum.click();
                break;
            }
        }
        sleep(ChatClient.overtime_2);
        //设置金额
        setClickM(list.get(0).getMoney());
        sleep(ChatClient.overtime_2);
        // 点击只能转账空白处关闭键盘 不区分机型
        mDevice.click(515, 160);
        sleep(ChatClient.overtime_2);
        AmountOfContrast();
    }

    private void AmountOfContrast() throws UiObjectNotFoundException {
        showLog("订单金额与输入金额对比");
        while (true) {
            UiObject cardSum = mDevice.findObject(new UiSelector().resourceId("TRANS_AMT").index(1));
            if (cardSum.exists()) {
                String money = cardSum.getText();
                if (Double.parseDouble(list.get(0).getMoney()) == Double.parseDouble(money.replaceAll(",", ""))) {
                    showLog("订单金额==" + list.get(0).getMoney() + "；" + "输入金额==" + cardSum.getText() + "--->金额相等");
                } else {
                    int length = cardSum.getText().length() + 1;
                    showLog("订单金额==" + list.get(0).getMoney() + "；" + "输入金额==" + cardSum.getText() + "--->金额不相等");
                    sleep(1000);
                    cardSum.click();
                    sleep(2000);
                    for (int i = 0; i < length; i++) {
                        mDevice.click(910, 1920);
                        sleep(500);
                    }
                    sleep(2000);
                    setClickM(list.get(0).getMoney());
                    sleep(1000);
                    // 点击只能转账空白处关闭键盘 不区分机型
                    mDevice.click(515, 160);
                    sleep(ChatClient.overtime_2);
                    AmountOfContrast();
                }
                break;
            }
        }
    }

    private int passwordUsage = 0;

    /**
     * 短信与转账密码处理
     */
    private void SMSOrPwd() throws UiObjectNotFoundException {
        addWorkTime(ChatClient.overtime_90);
        setPhoneSMS();
        sleep(ChatClient.overtime_2);
        //取款密码输入
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > 3000) {
                LogToFile.d("---点击取款密码的输入框失败---", "-----点击取款密码的输入框失败-----");
                break;
            }
            UiObject bpwd = mDevice.findObject(new UiSelector().resourceId("PASSWORD"));
            if (bpwd.exists()) {
                bpwd.click();
                sleep(ChatClient.overtime_2);
                LogToFile.d("---截取取款密码的键盘---", "-----截取取款密码的键盘-----");
                // 收起键盘
                passwordUsage = 0;
                getJpImg(user.getBankpwd());
                sleep(ChatClient.overtime_2);
                LogToFile.d("", "======================--------->");
                mDevice.click(1000, 1250);
                sleep(ChatClient.overtime_2);
                break;
            }
        }
        sleep(ChatClient.overtime_2);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                break;
            }
            UiObject button = mDevice.findObject(new UiSelector().text("确定").className("android.widget.Button").index(9));
            if (button.exists()) {
                showLog("确定");
                button.click();
                break;
            }
            UiObject button1 = mDevice.findObject(new UiSelector().descriptionContains("确定").className("android.widget" +
                    ".Button").index(9));
            if (button1.exists()) {
                showLog("确定");
                button1.click();
                break;
            }
        }
        sleep(ChatClient.overtime_5);
        errorSMSValidation();
    }

    /**
     * 转账错误处理
     */
    private void errorSMSValidation() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_8) {
                showLog("账单错误超时");
                break;
            }
            String errorMsg = errorMsg();
            if (!StringUtils.isEmpty(errorMsg)) {
                if (errorMsg.contains("错误")) {
                    if (smsFlag < 3) {
                        smsFlag++;
                        SMSOrPwd();
                        break;
                    } else {
                        ChatClient.timer(Constants.getMethod(0), "短息获取超过三次");
                        return;
                    }
                }
            }
        }
    }

    private String errorMsg() throws UiObjectNotFoundException {
        UiObject errorMsgTitle = mDevice.findObject(new UiSelector().resourceId("cn.bolz.mobilebank" +
                ".liuzhou:id/tips_dialog_tv_content"));
        UiObject errorMsgBtn;
        String errorResult;
        if (errorMsgTitle.exists()) {
            errorResult = errorMsgTitle.getText();
            showLog("errorMsg  = " + errorResult);
            errorMsgBtn = mDevice.findObject(new UiSelector().resourceId("cn.bolz.mobilebank.liuzhou:id/dialog_btn_cancel"));
            if (errorMsgBtn.exists()) {
                showLog("点击提示弹窗《确定》");
                errorMsgBtn.click();
                return errorResult;
            }
        }
        return "";
    }

    /**
     * 处理无SIM卡手机短信逻辑
     */
    private void setNotSIM_SMS() throws UiObjectNotFoundException {
        addWorkTime(ChatClient.overtime_90);
        sleep(ChatClient.overtime_10);
        SMSCode smsCode = requestSMSCode(user.getUserName(), user.getBankId());
        if (StringUtils.isEmpty(smsCode.getSmscode())) {
            sleep(ChatClient.overtime_20);
            smsCode = requestSMSCode(user.getUserName(), user.getBankId());
        }
        showLog("获取输入短信验证码输入框");
        while (true) {
            UiObject button = mDevice.findObject(new UiSelector().text("请输入短信验证码").resourceId("SMS").index(1));
            if (button.exists()) {
                showLog("输入短信验证码");
                button.click();
                break;
            }
        }
        sleep(ChatClient.overtime_3);
        // 点击切换数字
        mDevice.click(82, 1934);
        sleep(ChatClient.overtime_2);
        clickNumKey(smsCode.getSmscode());
    }

    /**
     * 监听短信点击输入验证码
     */
    private void setPhoneSMS() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_90) {
                showLog("获取验证码失败");
                ChatClient.timer(LogToFile.getMethodName(), "短信验证码超时错误");
                break;
            }
            UiObject button = mDevice.findObject(new UiSelector().text("获取验证码").className("android.widget.Button").index(2));
            if (button.exists()) {
                showLog("获取验证码");
                button.click();
                break;
            }
            UiObject button1 = mDevice.findObject(new UiSelector().text("重新发送").className("android.widget.Button").index(2));
            if (button1.exists()) {
                showLog("重新获取验证码");
                button1.click();
                break;
            }
        }
        if (user.getUseType().equals("1")) {
            showLog("处理转账短信---真机");
            ChatClient.begintime = System.currentTimeMillis();
            while (true) {
                long nowTime1 = System.currentTimeMillis();
                if (nowTime1 - ChatClient.begintime > ChatClient.overtime_90) {
                    ChatClient.timer(LogToFile.getMethodName(), "短信验证码超时错误");
                    break;
                }
                if (TextUtils.isEmpty(Constants.CODE)) {
                    sleep(ChatClient.overtime_3);
                } else {
                    showLog("返回短信验证码为：" + Constants.CODE);
                    break;
                }
            }
            showLog("获取输入短信验证码输入框");
            while (true) {
                UiObject button = mDevice.findObject(new UiSelector().text("请输入短信验证码").resourceId("SMS").index(1));
                if (button.exists()) {
                    showLog("输入短信验证码");
                    button.click();
                    break;
                }
            }
            sleep(ChatClient.overtime_3);
            // 点击切换数字
            mDevice.click(82, 1934);
            sleep(ChatClient.overtime_2);
            clickNumKey(Constants.CODE);
            Constants.CODE = null;
        } else {
            showLog("处理转账短信---无SIM卡");
            setNotSIM_SMS();
        }

    }

    /**
     * 点击收款账号
     *
     * @param bankNo 账号
     */
    private void clickNumKey(String bankNo) {
        try {
            char[] num = "1234567890".toCharArray();//char数组
            char[] money = bankNo.toCharArray();//char数组

            for (char c : money) {
                for (int i = 0; i < num.length; i++) {
                    if (num[i] == c) {
                        mDevice.click(xy_Card_Number[i][0], xy_Card_Number[i][1]);
                        sleep(ChatClient.overtime_1);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        showLog("短信验证码输入完成，收回键盘");
        mDevice.click(990, 1250);
    }

    /**
     * 字母和数字键盘的切换
     *
     * @param checkStr 字符串
     * @return true字母  false特殊字符
     */
    private boolean isNumericZF(String checkStr) {
        return checkStr.contains("#") || checkStr.contains("*") || checkStr.contains("&") || checkStr.contains("@");
    }

    /**
     * 登陆密码
     *
     * @param pad 登陆密码
     */
    private void setClick_new(String pad) {
        Exception exception = new Exception();
        StackTraceElement[] trace = exception.getStackTrace();
        String method = trace[0].getMethodName();
        try {
            char[] abc = "qwertyuiopasdfghjklzxcvbnm".toCharArray();//char数组
            char[] zf = "#*&@".toCharArray();//char数组
            char[] pwd = pad.toCharArray();//char数组
            char[] num_abc;//char数组
            sleep(ChatClient.overtime_2);
            for (char c : pwd) {
                if (isNumericZF(String.valueOf(c))) {
                    num_abc = zf;
                } else {
                    num_abc = abc;
                }
                for (int i = 0; i < num_abc.length; i++) {
                    if (num_abc[i] == c) {
                        if (isNumericZF(String.valueOf(c))) {
                            clickSpecialCharacter();
                            sleep(ChatClient.overtime_1);
                            mDevice.click(xy_zf[i][0], xy_zf[i][1]);
                            sleep(ChatClient.overtime_1);
                        } else {
                            clickLetter();
                            sleep(ChatClient.overtime_1);
                            mDevice.click(xy_abc[i][0], xy_abc[i][1]);
                            sleep(ChatClient.overtime_1);
                        }
                        break;
                    }
                }
            }
        } catch (Exception e) {
            showLog("点击特殊字符=======为空");
            ChatClient.timer(method, "");
        }
    }

    /**
     * 点击特殊字符
     */
    private void clickSpecialCharacter() {
        mDevice.click(950, 1330);
    }

    /**
     * 点击字母
     */
    private void clickLetter() {
        mDevice.click(777, 1330);
    }

    /**
     * 模拟点击密码
     *
     * @param pad_ 要点击的
     */
    private void setClick_pwd(List<PointBean> pointBeanList, String pad_) {
        StringBuilder tempStr = new StringBuilder();
        if (pointBeanList.size() > 0) {
            for (int i = 0; i < pointBeanList.size(); i++) {
                tempStr.append(pointBeanList.get(i).getCharStr());
            }
        }
        char[] abc_num = tempStr.toString().toCharArray();//字母或者数字数组
        char[] pwd = pad_.toCharArray();//要点击的密码char数组
        if (passwordUsage < 4) {
            if (StringUtils.isEmpty(tempStr.toString())) {
                getJpImg(user.getBankpwd());
            }
        }
        for (char c : pwd) {
            for (int i = 0; i < abc_num.length; i++) {
                if (abc_num[i] == c) {
                    sleep(ChatClient.overtime_1);
                    //点击数字
                    int num = pointBeanList.get(i).getY();
                    mDevice.click((pointBeanList.get(i).getX()), num + 1380);
                }
            }
        }
    }

    /**
     * 境内汇款页面
     */
    private void remittance() throws UiObjectNotFoundException {
        sleep(ChatClient.overtime_3);
        while (true) {
            UiObject skr = mDevice.findObject(new UiSelector().resourceId("pageA").index(0).text("智能转账"));
            if (skr.exists()) {
                showLog("检测进入已转账页面");
                break;
            }
            UiObject skr1 = mDevice.findObject(new UiSelector().resourceId("pageA").index(0).descriptionContains("智能转账"));
            if (skr1.exists()) {
                showLog("检测进入已转账页面");
                break;
            }
        }
        sleep(ChatClient.overtime_2);
        //进入转账页面
        getTheBalance(true);
        sleep(ChatClient.overtime_2);
        LogToFile.d("请求订单", "请求订单");
        ChatClient.request();
        if (ChatClient.waitExistOrder(ChatClient.overtime_60)) {
            orderBankName = Constants.getBank(list.get(0).getBankName(), "CIB");
            // 转账
            showLog("进入转账");
            remittanceLogin();
            return;
        }
        mDevice.pressBack();
        sleep(ChatClient.overtime_3);
    }

    /**
     * 查账
     */
    private void auditOrder() throws UiObjectNotFoundException {
        addWorkTime(ChatClient.overtime_60);
        sleep(ChatClient.overtime_5);
        //进入转账页面
        getTheBalance(false);
        sleep(ChatClient.overtime_3);
        mDevice.pressBack();
        sleep(ChatClient.overtime_3);
        showLog("准备点击------>转账记录");
        while (true) {
            UiObject seeTheHistory = mDevice.findObject(new UiSelector().className("android.view.View").index(2).text
                    ("转账记录"));
            if (seeTheHistory.exists()) {
                seeTheHistory.click();
                break;
            }
            sleep(ChatClient.overtime_3);
        }
        showLog("准备点击------>查询");
        while (true) {
            UiObject transfer = mDevice.findObject(new UiSelector().className("android.widget.Button").index(3).text("查询"));
            if (transfer.exists()) {
                transfer.click();
                break;
            }
            sleep(ChatClient.overtime_3);
        }
        sleep(ChatClient.overtime_8);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowTime = System.currentTimeMillis();
            if ((nowTime - ChatClient.begintime) > ChatClient.overtime_10) {
                showLog("没有记录");
                newAuditProcess();
                return;
            }
            UiObject scrollView = mDevice.findObject(new UiSelector().resourceId("pageB").index(0).text("转账交易记录"));
            UiObject listView = scrollView.getChild(new UiSelector().className("android.widget.ListView").index(1));
            if (listView.exists()) {
                showLog("有转账记录");
                listView.click();
                break;
            }
        }
        sleep(ChatClient.overtime_3);
        String money;
        String userName;
        String bankNo;
        String results;
        //获取交易记录
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            sleep(ChatClient.overtime_2);
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_30) {
                newAuditProcess();
                sleep(ChatClient.overtime_2);
                mDevice.pressBack();
                return;
            }
            ChatClient.begintime = System.currentTimeMillis();//开始时间
            UiObject checkAccounts = mDevice.findObject(new UiSelector().resourceId("pageC").text("转账交易记录").index(0));
            if (checkAccounts.exists()) {
                //查询
                UiObject textView2 = checkAccounts.getChild(new UiSelector().className("android.view.View").index(15));
                UiObject textView4 = checkAccounts.getChild(new UiSelector().className("android.view.View").index(3));
                UiObject textView6 = checkAccounts.getChild(new UiSelector().className("android.view.View").index(13));
                userName = textView2.getText();
                money = textView4.getText().substring(0, textView4.getText().length() - 1);
                bankNo = textView6.getText().substring(textView6.getText().length() - 4);
                UiObject textView5 = checkAccounts.getChild(new UiSelector().className("android.view.View").instance(19));
                results = textView5.getText();
                LogToFile.d("====---results-====", "====results===:" + results);
                break;
            }
        }
        String money1 = money.replaceAll(",", "");
        LogToFile.d(BANK_NAME, Double.parseDouble(list.get(0).getMoney()) + "====" + Double.parseDouble(money1));

        if (Double.parseDouble(list.get(0).getMoney()) == Double.parseDouble(money1) && userName.contains(list.get(0)
                .getUserName()) && list.get(0).getBankNo().contains(bankNo)) {
            failureToReport(results, Constants.getStr(results));
            back();
        } else {
            newAuditProcess();
        }
        sleep(ChatClient.overtime_2);
        mDevice.pressBack();
    }

    /**
     * 查账时走金额变化判断  使用地方为：1、未找到和上一笔订单相同的金额和名称的订单 2、查账时出现异常超时 3、没有记录时
     */
    private void newAuditProcess() {
        showLog("未查到相同订单");
        String sumMoneyFile = user.getUserName() + BANK_NAME + "_sumMoney.txt";
        String oldMoney = FileHelper.readSDFile(sumMoneyFile);
        switch (Constants.changeInAmount(BANK_NAME, oldMoney, sumMoney, list.get(0).getMoney())) {
            case "0":
                failureToReport("交易成功", 0);
                break;
            case "1":
                failureToReport("交易待处理...", 1);
                break;
            case "4":
                failureToReport("未查到条目", 4);
                break;
        }
        back();
    }

    private void failureToReport(String info, int state) {
        String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'" + BANK_NAME +
                "'," + "'info':'" + info + "'";
        String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + sumMoney + "','state':" + state + "," +
                "'type':1";
        showLog("mobileD = " + mobileD);
        showLog("json = " + json);
        ChatClient.msg("<YZF>{'header':'" + ChatClient.S_CONFIRM_TRADE_RESULT_C + "'," + json + "," + mobileD + "}</YZF>");
        //删除处理过的订单
        mapDelete(list.get(0).getOrder());
        getmap();
        sleep(ChatClient.overtime_2);
    }

    /**
     * 完成转账后回复服务端
     */
    private void getUserInfo() throws UiObjectNotFoundException {
        Exception exception = new Exception();
        StackTraceElement[] trace = exception.getStackTrace();
        String method = trace[0].getMethodName();
        String balance;
        String type = "";
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        LogToFile.d("=====getUserInfo====", "=====getUserInfo====");
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(method, ChatClient.errorStr);
                break;
            }
            //  获取交易结果 柳州银行无交易完成，交易中。。。。只有交易已提交到对方账户  梁钊
            UiObject state1 = mDevice.findObject(new UiSelector().text("智能转账").resourceId("pageD"));
            if (state1.exists()) {
                UiObject textView = state1.getChild(new UiSelector().className("android.view.View").index(1));
                if (textView.exists()) {
                    type = textView.getText().substring(textView.getText().length() - 4);
                }
                break;
            }
        }
        LogToFile.d("=====确定收款银行====", "=====转账完成====" + type);
        if (Constants.getStr(type) == 0) {
            DecimalFormat formater = new DecimalFormat("#0.##");
            balance = formater.format(Double.parseDouble(sumMoney) - Double.parseDouble(list.get(0).getMoney()));
            showLog("保存余额...");
            String sumMoneyFile = user.getUserName() + BANK_FLAG + "_sumMoney.txt";
            FileHelper.saveMoneySDFile(false, sumMoney, sumMoneyFile);
        } else {
            balance = sumMoney;
        }
        type = type.replaceAll("\r|\n|\\s", "");
        String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'" + BANK_NAME +
                "'," + "'info':'" + type + "'";
        String json;
        showLog("mobileD = " + mobileD);
        if (Constants.getStr(type) == 0) {
            json = "'order':'" + list.get(0).getOrder() + "','balance':'" + balance + "','state':" + Constants.getStr(type) +
                    ",'type':1";
        } else {
            json = "'order':'" + list.get(0).getOrder() + "','balance':'" + balance + "','state':" + Constants.getStr(type) +
                    ",'type':1";
        }
        showLog("json = " + json);
        ChatClient.msg("<YZF>{'header':'" + ChatClient.M_SEND_TRADE_RESULT_P + "'," + json + "," + mobileD + "}</YZF>");
        //删除处理过的订单
        mapDelete(list.get(0).getOrder());
        getmap();
        sleep(ChatClient.overtime_2);
        showLog("滑动屏幕");
        mDevice.drag(50, 500, 50, 200, 20);
        sleep(ChatClient.overtime_2);
        //返回
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime) {
                ChatClient.timer(method, ChatClient.errorStr);
                break;
            }
            UiObject state0 = mDevice.findObject(new UiSelector().text("再转一笔").className("android.widget.Button"));
            if (state0.exists()) {
                LogToFile.d("====结果页====", "====点击继续转账====");
                state0.click();
                break;
            }
        }
        Constants.CODE = "";
        sleep(2000);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_5) {
                showLog("进入转账汇款页失败");
                ChatClient.timer(Constants.getMethod(0), ChatClient.errorStr);
                return;
            }
            UiObject webView = mDevice.findObject(new UiSelector().text("卡号转账").className("android.view.View"));
            if (webView.exists()) {
                webView.click();
                sleep(ChatClient.overtime_2);
                break;
            }
        }
    }

    /**
     * 模拟点击金额
     */
    private void setClickM(String money_) {
        try {
            char[] num = "123456789.0".toCharArray();//char数组
            char[] money = money_.toCharArray();//char数组

            for (char c : money) {
                for (int i = 0; i < num.length; i++) {
                    if (num[i] == c) {
                        mDevice.click(xy_123m[i][0], xy_123m[i][1]);
                        sleep(ChatClient.overtime_1);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 模拟输入账户
     */
    private void setClickCardNumber(String money_) {
        try {
            char[] num = "1234567890".toCharArray();//char数组
            char[] money = money_.toCharArray();//char数组

            for (char c : money) {
                for (int i = 0; i < num.length; i++) {
                    if (num[i] == c) {
                        mDevice.click(xy_Card_Number[i][0], xy_Card_Number[i][1]);
                        sleep(ChatClient.overtime_1);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 截去英文键盘模拟用户输入密码
     * U盾密码字母键盘
     *
     * @param pwd:要点击的密码
     */
    private void getJpImg(String pwd) {
        passwordUsage++;
        List<PointBean> pointBeanList;
        try {
            LogToFile.d("========", "截图=" + screenHeight);
            Bitmap bitmap = ImageView.getImage1(0, 1380, 1080, 2016, 1080, 636);
            String bankName = "LZB";
            pointBeanList = saveImg22(bitmap, bankName);
            setClick_pwd(pointBeanList, pwd);
        } catch (Exception e) {
            setDevicesLog(e.getCause().getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 返回
     */
    private void back() {
        LogToFile.d("====转账详情页====", "====返回主页====");
        mDevice.pressBack();
        sleep(ChatClient.overtime_2);
        mDevice.pressBack();
    }

    private void showLog(String msg) {
        LogToFile.showLog(BANK_NAME, msg);
    }
}
